import 'package:flutter/material.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';
import 'package:provider/provider.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'dart:async';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';
import 'package:labcloud_app/data/user.dart';

import '../../api/graphql_config.dart';
import '../../config/token_storage.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login>
    with SingleTickerProviderStateMixin {
  bool _isPasswordLogin = true; // true为密码登录，false为验证码登录
  bool _isSendingCode = false; // 是否正在发送验证码
  int _countdown = 0; // 倒计时时间
  Timer? _timer; // 倒计时定时器，改为可空类型

  // 控制器
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  // 添加默认值常量
  static const String _defaultUsername = 'userwu';
  static const String _defaultPassword = '123456';


  @override
  void initState() {
    super.initState();

    // 设置默认值
    _usernameController.text = _defaultUsername;
    _passwordController.text = _defaultPassword;
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _emailController.dispose();
    _codeController.dispose();
    // 取消定时器
    _timer?.cancel(); // 使用?.操作符安全地调用cancel
    super.dispose();
  }

  // 发送验证码
  void _sendVerificationCode() async {
    // TODO: 实现发送验证码的逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('发送验证码功能待实现')),
    );
  }

  // 切换登录方式
  void _toggleLoginMethod() {
    setState(() {
      _isPasswordLogin = !_isPasswordLogin;
    });
  }

  // 用户名密码登录
  Future<void> _loginWithUsernameAndPassword({
    required String username,
    required String password,
  }) async {
    final userModel = Provider.of<UserModel>(context, listen: false);
    
    // 获取GraphQL客户端
    final client = GraphQLProvider.of(context).value;
    
    final result = await client.mutate(
      MutationOptions(
        document: gql(UserGQL.fetchLoginUser),
        variables: {
          'username': username,
          'password': password,
        },
      ),
    );

    if (result.hasException) {
      final errorMessage = '登录失败: ${result.exception.toString()}';
      print('登录错误: $errorMessage'); // 打印到日志
      throw Exception(errorMessage);
    }

    final user = User.fromJson(result.data!['user']['loginUser']);

    // 保存token
    TokenStorage.saveTokens(user.accessToken!, user.refreshToken!);
    user.refreshToken = '';
    user.accessToken = '';
    userModel.setUser(user);
    await userModel.saveUserToStorage(); // 保存到持久化存储
  }

  // 邮箱验证码登录
  Future<void> _loginWithEmailAndCode({
    required String email,
    required String code,
  }) async {
    final userModel = Provider.of<UserModel>(context, listen: false);
    
    // 获取GraphQL客户端
    final client = GraphQLProvider.of(context).value;
    
    // TODO: 实现邮箱验证码登录逻辑
    // 这里应该调用相应的GraphQL mutation
    print('使用邮箱 $email 和验证码 $code 登录');
    
    // 示例代码 - 实际应该调用相应的GraphQL mutation
    // final result = await client.mutate(
    //   MutationOptions(
    //     document: gql(UAAService.fetchLoginByEmail),
    //     variables: {
    //       'email': email,
    //       'code': code,
    //     },
    //   ),
    // );
    //
    // if (result.hasException) {
    //   throw Exception('登录失败: ${result.exception.toString()}');
    // }
    //
    // final user = User.fromJson(result.data!['user']['loginUser']);
    // userModel.setUser(user);
    // await userModel.saveUserToStorage(); // 保存到持久化存储
  }

  // 登录处理
  void _handleLogin() async {
    if (_isPasswordLogin) {
      // 密码登录
      if (_usernameController.text.isEmpty ||
          _passwordController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('请输入用户名和密码')),
        );
        return;
      }

      // 显示加载提示
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        },
      );

      try {
        await _loginWithUsernameAndPassword(
          username: _usernameController.text.trim(),
          password: _passwordController.text.trim()
        );

        // 隐藏加载提示
        Navigator.of(context).pop();

        // 登录成功，返回上一页
        Navigator.of(context).pop(true);
      } catch (e) {
        // 隐藏加载提示
        Navigator.of(context).pop();

        // 登录失败
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('登录失败: $e')),
        );
      }
    } else {
      // 验证码登录
      if (_emailController.text.isEmpty || _codeController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('请输入邮箱和验证码')),
        );
        return;
      }

      // 显示加载提示
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        },
      );

      try {
        await _loginWithEmailAndCode(
          email: _emailController.text.trim(),
          code: _codeController.text.trim()
        );

        // 隐藏加载提示
        Navigator.of(context).pop();

        // 登录成功，返回上一页
        Navigator.of(context).pop(true);
      } catch (e) {
        // 隐藏加载提示
        Navigator.of(context).pop();

        // 登录失败
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('登录失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            const SizedBox(height: 30),
            _buildLoginPage(),
            const SizedBox(height: 20),
            // 添加跳转到注册页面的按钮
            TextButton(
              onPressed: () {
                // 跳转到注册页面
                Navigator.pushNamed(context, '/register');
              },
              child: const Text(
                '还没有账号？立即注册',
                style: TextStyle(
                  color: Colors.blue,
                  fontSize: 16,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建登录页面
  Widget _buildLoginPage() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // 登录方式切换按钮
        _buildLoginMethodToggle(),
        const SizedBox(height: 20),

        // 用户名/邮箱输入框
        TextField(
          controller: _isPasswordLogin ? _usernameController : _emailController,
          decoration: InputDecoration(
            labelText: _isPasswordLogin ? '用户名' : '邮箱',
            border: const OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(30)),
            ),
            prefixIcon: Icon(
              _isPasswordLogin ? Icons.person : Icons.email,
            ),
          ),
        ),
        const SizedBox(height: 20),

        // 密码或验证码输入框
        _isPasswordLogin
            ? TextField(
          controller: _passwordController,
          obscureText: true,
          decoration: const InputDecoration(
            labelText: '密码',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(30)),
            ),
            prefixIcon: Icon(Icons.lock),
          ),
        )
            : Row(
          children: [
            Expanded(
              child: TextField(
                controller: _codeController,
                decoration: const InputDecoration(
                  labelText: '验证码',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(30)),
                  ),
                  prefixIcon: Icon(Icons.lock),
                ),
              ),
            ),
            const SizedBox(width: 10),
            ElevatedButton(
              onPressed: _isSendingCode || _countdown > 0 ? null : _sendVerificationCode,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
              child: _isSendingCode
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : Text(_countdown > 0 ? '$_countdown秒后重发' : '发送验证码'),
            ),
          ],
        ),
        const SizedBox(height: 30),

        // 登录按钮
        _buildActionButton('登录', _handleLogin),
      ],
    );
  }

  // 构建登录方式切换控件（优化版）
  Widget _buildLoginMethodToggle() {
    return Container(
      height: 50,
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(25),
      ),
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              onTap: () {
                if (!_isPasswordLogin) {
                  setState(() {
                    _isPasswordLogin = true;
                  });
                }
              },
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 300),
                margin: EdgeInsets.all(_isPasswordLogin ? 2 : 5),
                decoration: BoxDecoration(
                  color: _isPasswordLogin ? Colors.blue : Colors.transparent,
                  borderRadius: BorderRadius.circular(25),
                ),
                alignment: Alignment.center,
                child: Text(
                  '账号密码',
                  style: TextStyle(
                    color: _isPasswordLogin ? Colors.white : Colors.black54,
                    fontWeight: _isPasswordLogin ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: GestureDetector(
              onTap: () {
                if (_isPasswordLogin) {
                  setState(() {
                    _isPasswordLogin = false;
                  });
                }
              },
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 300),
                margin: EdgeInsets.all(!_isPasswordLogin ? 2 : 5),
                decoration: BoxDecoration(
                  color: !_isPasswordLogin ? Colors.blue : Colors.transparent,
                  borderRadius: BorderRadius.circular(25),
                ),
                alignment: Alignment.center,
                child: Text(
                  '邮箱验证码',
                  style: TextStyle(
                    color: !_isPasswordLogin ? Colors.white : Colors.black54,
                    fontWeight: !_isPasswordLogin ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建操作按钮（登录）
  Widget _buildActionButton(String text, VoidCallback onPressed) {
    return Container(
      height: 56,
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(28),
      ),
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(28),
          ),
          padding: EdgeInsets.zero,
          elevation: 0,
        ),
        child: Text(
          text,
          style: const TextStyle(
            fontSize: 18,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}